<?php


namespace App\Http\Controllers;


use App\Helpers\Helpers;
use App\Model\Cart;
use App\Model\Goods;
use Illuminate\Database\Eloquent\Collection;
use Sample\PayPalClient;
use test\Mockery\Fixtures\MethodWithVoidReturnType;

class GoodsController extends Controller
{

    public function info($id)
    {
        $id = intval($id);
        $goods = Goods::find($id);
        if (empty($goods)) {
            abort(404);
        }

//        if (request()->query() && $goods->out_url) {
//            return redirect($goods->out_url);
//        }

        // 查询商品相关推荐
        $recGoods = Goods::where('category_id', $goods->category_id)->where('id', '<>', $goods->id)->limit(5)->get();

        return view('home.goods', [
            'goods' => $goods,
            'rec_goods' => $recGoods,
            'url' => request()->query() && $goods->out_url ? $goods->out_url : '/products/' . $goods->id
        ]);
    }

    public function preview($id)
    {
        $id = intval($id);
        $goods = Goods::find($id);
        if (empty($goods)) {
            abort(404);
        }

        // 添加商品到购物车购物车
        Cart::AddGoodsCart($goods);

        // 查询购物车状态
        /** @var Cart[]|Collection $carts */
        $carts = Cart::with('goods')->where('user_id', Helpers::getUserId())->get();

        $total = 0;
        foreach ($carts as $cart) {
            $total = $total + $cart->number * $cart->goods->goods_price;
        }

        return view('home.preview', [
            'goods' => $goods,
            'count' => $carts->count(),
            'total' => number_format($total, 2),
        ]);
    }

}
